<template>
  <TresPerspectiveCamera :position="[0, 12, 0]" :look-at="[0, 0, 0]" />
  <TresAmbientLight :position="[0, 12, 0]" :intensity="200" color="red" />
  <TresDirectionalLight :position="[1, 1, 0]" :intensity="3" />

  <!-- <TresMesh ref="boxRef" :position="[0, 2, 0]">
    <TresBoxGeometry :args="[1, 1, 1]" />
    <TresMeshNormalMaterial />
  </TresMesh> -->
  <!-- 使用 FbxModel 组件 -->
  <!-- <TresGLB url="./model/SK_FuQian_A.glb">
    <TresMesh :position="[0, -2, 0]" :scale="[0.5, 0.5, 0.5]">
      <TresMeshStandardMaterial :metalness="0.8" :roughness="0.2" />
    </TresMesh>
  </TresGLB> -->
  <!-- <TresMesh>
    <TresBoxGeometry />
    <TresMeshStandardMaterial v-if="texture" :map="texture" />
  </TresMesh> -->
  <!-- <TresMesh
    :position="[-0.5, 1, 0]"
    :rotation="[
      Math.PI * (0 / 180),
      Math.PI * (130 / 180),
      Math.PI * (0 / 180),
    ]"
  >
  </TresMesh> -->
  <primitive v-if="rig" ref="boxRef" :object="rig"> </primitive>

  <!-- <GLTFModel ref="boxRef" path="./model/SK_FuQian_A1.glb"> </GLTFModel> -->

  <TresAxesHelper />
  <TresGridHelper :args="[10, 10]" />
</template>

<script setup lang="ts">
// 导入整个 THREE 命名空间
import * as THREE from "three";
import { TextureLoader } from "three";
import type { TresObject } from "@tresjs/core";
import { useLoop, useGraph, useLoader } from "@tresjs/core";
import { computed, shallowRef, watch } from "vue";
import { useAnimations, useGLTF, GLTFModel, useTexture } from "@tresjs/cientos";

const { onBeforeRender } = useLoop();
const boxRef = shallowRef<TresObject | null>(null);
const { state: model, nodes } = useGLTF("./model/SK_FuQian_A.glb");
// console.log("model:", model);
// 方法1: 加载单张纹理

// const { state: texture, isLoading, error } = useTexture("./ui/normal.png");
const { state: texture } = await useTexture("./ui/normal.png");

// Load a texture from a remote URL
// const {
//   state: texture,
//   isLoading,
//   error,
// } = useLoader(TextureLoader, "./ui/content.png");

watch(
  () => boxRef.value,
  () => {
    if (!boxRef.value) return;
    console.log("boxRef.value:", boxRef.value);
    // console.log("model:", model.value);
    const scene = boxRef?.value?.instance;
  },
  { deep: true }
);

const animations = computed(() => model.value?.animations || []);
const rig = computed(() => {
  return nodes.value.Scene;
});

const { actions } = useAnimations(animations, rig);
watch(
  () => actions,
  () => {
    if (!actions) return;
    console.log("actions:", actions);
    Object.values(actions)?.forEach((item) => {
      item.setLoop(THREE.LoopOnce); // 设置为仅播放一次
      item.play();
    });
  },
  { deep: true }
);

// const scene = computed(() => model.value?.scene);
// const { materials } = useGraph(scene);

watch(
  () => boxRef,
  () => {
    if (boxRef) {
      console.log("boxRef.position:", boxRef.position);
    }
  },
  { deep: true }
);
// materials.FancyMaterial.color.set("purple");

defineExpose({
  actions,
});
</script>
